import React, {useState, useEffect, useMemo, useRef} from 'react';
import {View, StyleSheet, processColor} from 'react-native';
import {useTranslation} from 'react-i18next';
import {AppPvTimeIndicatorDTO, deviceApi} from '@/services/api/deviceApi';
import dayjs from 'dayjs';
import LineChart from '@/components/LineChart';
import Segmented from '@/components/Segmented';
import {Card} from 'tsun-smart-ui';
import toast from '@/utils/toast';
import {hexWithOpacity} from '@/utils';
import {selectCurrentDevice} from '@/store/slices/deviceSlice';
import {useSelector} from 'react-redux';
import CustomLegend from '@/components/CustomLegend';
import {ColorItem} from '@/store/slices/landscapeColorsSlice';
import {LineChart as LineChartWrapper} from '@see_you/react-native-charts-wrapper';
type ChartType = 'outPower' | 'outVoltage' | 'outCurrent';

const Chart = ({
  data,
  unit,
  pvNum,
  type,
}: {
  pvNum: number;
  unit: string;
  type: ChartType;
  data: AppPvTimeIndicatorDTO;
}) => {
  const {t} = useTranslation();
  const color = [
    '#FF891F',
    '#1FC16B',
    '#338BFF',
    '#F5C227',
    '#F75455',
    '#3776F5',
  ];
  const [colors, setColors] = useState<ColorItem[]>(
    Array.from({length: pvNum}, (_, index) => ({
      title: `out${index + 1}`,
      color: color[index],
      visible: true,
    })),
  );
  const chartData = useMemo(() => {
    const originData = Object.entries(data);
    const xAxisLabels = originData[0]?.[1]?.map(item => item.time) ?? [];
    const values = originData.map(item =>
      (item?.[1] ?? []).map(item => item[type] ?? 0),
    );
    return {
      xAxisLabels,
      values,
    };
  }, [data, type]);
  const chartRef = useRef<LineChartWrapper>(null);
  useEffect(() => {
    chartRef.current?.fitScreen()
    chartRef.current?.highlights([])
  }, [type]);
  return (
    <>
      <View className="w-full" style={[{aspectRatio: 4 / 3}]}>
        <LineChart
          leftUnit={`${t('workplace.unit')}:${unit}`}
          xAxisLabels={chartData.xAxisLabels}
          chartData={chartData.values}
          showLegend={false}
          ref={chartRef}
          marker={`${t('sys.app.time')}: `}
          title={colors.map(item => item.title)}
          dataSetsConfig={colors.map(item => ({
            color: processColor(item.color),
            drawValues: false,
            drawCircles: false,
            visible: item.visible,
            fillGradient: {
              colors: [
                processColor(hexWithOpacity(item.color, 0)),
                processColor(hexWithOpacity(item.color, 0.4)),
              ],
              orientation: 'BOTTOM_TOP',
            },
            fillAlpha: 100,
          }))}
          yAxis={{
            left: {
              drawAxisLine: false,
            },
            right: {
              enabled: false,
            },
          }}
          scaleYEnabled={false}
        />
      </View>
      <CustomLegend colors={colors} setColors={setColors}></CustomLegend>
    </>
  );
};

const EquipTimeChart = () => {
  const {t} = useTranslation();
  const [selected, setSelected] = useState('outPower');
  const currentDevice = useSelector(selectCurrentDevice);
  const [data, setData] = useState<AppPvTimeIndicatorDTO>({});

  // 设置标题栏样式

  useEffect(() => {
    const fetchData = async () => {
      try {
        toast.showLoading();
        const [year, month, day] = dayjs().format('YYYY-MM-DD').split('-');
        const {data: responseData} = await deviceApi.getEquipTimeIndicator({
          deviceSns: [currentDevice?.sn!],
          deviceType: currentDevice?.deviceType!,
          stationId: currentDevice?.stationId!,
          grain: 0,
          year: year,
          month: month,
          day: day,
        });
        setData(responseData);
      } catch (error) {
        console.error('Failed to fetch PV time data:', error);
      } finally {
        toast.hideLoading();
      }
    };

    fetchData();
  }, []);
  const chartTypes = [
    {
      value: 'outPower',
      label: t('device.power', {defaultValue: '功率'}),
      unit: 'W',
    },
    {
      value: 'outVoltage',
      label: t('syslog.voltage', {defaultValue: '电压'}),
      unit: 'V',
    },
    {
      value: 'outCurrent',
      label: t('syslog.current', {defaultValue: '电流'}),
      unit: 'A',
    },
  ] as const;

  const getCurrentChart = () => {
    const chart = chartTypes.find(item => item.value === selected);
    return {
      unit: chart?.unit || '',
      value: chart?.value,
    };
  };
  const {unit, value} = getCurrentChart();
  return (
    <Card className="mx-4 mt-2 items-center">
      <View style={styles.header}>
        <Segmented
          value={selected}
          onChange={setSelected}
          buttons={chartTypes.map(type => ({
            value: type.value,
            label: type.label,
          }))}
        />
      </View>

      <Chart
        pvNum={currentDevice?.outList?.length ?? 0}
        unit={unit}
        type={value!}
        data={data}></Chart>
    </Card>
  );
};

const styles = StyleSheet.create({
  header: {
    marginBottom: 20,
  },
});

export default EquipTimeChart;
